package com.qf.common.web.interceptor;

import com.qf.common.core.utils.BaseUserUtils;
import com.qf.common.core.utils.UserInfo;
import com.qf.data.entity.auth.base.BaseUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Optional;

/**
 * 封装登录认证的信息
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class AuthInterceptor extends HandlerInterceptorAdapter {

    /**
     * 前置处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String json = request.getHeader("user_info");
        String fromType = request.getHeader("fromType");

        Optional.ofNullable(json)
                .map(js -> {
                    try {
                        return URLDecoder.decode(js, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    return null;
                }).ifPresent(js -> {
                    Assert.notNull(fromType, "fromType must not null");
                    //转换成SysUserVo对象
//                    SysUserVo sysUserVo = JsonUtils.json2Obj(js, SysUserVo.class);
                    BaseUser baseUser = BaseUserUtils.createUser(js, Integer.parseInt(fromType));
                    log.debug("[Auth-interceptor] - 认证拦截器获取到认证通过的用户信息 - {}", baseUser);
                    //放入工具类中
                    UserInfo.setUser(baseUser);
                });

        return super.preHandle(request, response, handler);
    }

    /**
     * 后置完成方法
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空用户信息
        UserInfo.clear();
        super.afterCompletion(request, response, handler, ex);
    }
}
